package pers.xdrodger.simple.test.ppt.apose;

import com.spire.presentation.*;

import java.util.HashMap;
import java.util.Map;

public class ReplaceText {

    public static void main(String[] args) throws Exception {

        //创建Presentation对象
        Presentation presentation = new Presentation();

        //加载示例文档
        presentation.loadFromFile("D:\\workspace\\practice-demo\\file\\input\\ppt-demo-替换文本.pptx");

        //获取第一张幻灯片
        ISlide slide= presentation.getSlides().get(0);

        //创建Map对象
        Map<String, Object> map = new HashMap();

        //将需要被替换和用于替换的文本以键值的形式添加到Map
        map.put("#姓名#","小明");
        map.put("#年龄#","28");
        map.put("#地址#","成都市");
        map.put("#电话#","028-12345678");
        map.put("#邮箱#","xiaoming @163.com");

        //替换幻灯片中的文本
        replaceText(slide,map);

        //保存文档
        presentation.saveToFile("D:\\workspace\\practice-demo\\file\\output\\ppt-demo-替换文本-output.pptx", FileFormat.PPTX_2013);
    }

    /**
     * 替换指定幻灯片中的文本
     */
    public static void replaceText(ISlide slide, Map<String, Object> map) {

        for (Object shape : slide.getShapes()
        ) {
            if (shape instanceof IAutoShape) {

                for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
                ) {
                    ParagraphEx paragraphEx = (ParagraphEx) paragraph;
                    for (String key : map.keySet()
                    ) {
                        if (paragraphEx.getText().contains(key)) {

                            paragraphEx.setText(paragraphEx.getText().replace(key, (String) map.get(key)));
                        }
                    }
                }
            }
        }
    }
}